package hjw.com.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTCreationException;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author maste
 */
public class JwtUtil {

    public static final String TOKEN_HEADER = "Authorization";
    public static final String TOKEN_PREFIX = "Bearer";
    /**签名的加密的密码，服务器知道即可*/
    private static final String JWT_SECRET = "03hjw1103";
    /**生成的token过期时间不超过 EXPIRE_TIME*/
    private static final long EXPIRE_TIME = 24 * 60 * 60 * 1000;

    /**
     * 生成签名
     * @param username 用户名
     * @return 加密后的token
     */
    public static String createToken(String username, List<String> roleList){
        Date tokenOutTime = new Date(System.currentTimeMillis() + EXPIRE_TIME);
        String roles = "";
        for (String s : roleList) {
            roles = roles + s + ",";
        }
        try {
            Algorithm algorithm = Algorithm.HMAC256(JWT_SECRET);
            return JWT.create()
                    .withClaim("username",username)//用户编号 主键
                    .withClaim("roles",roles)// 用户权限范围
                    .withExpiresAt(tokenOutTime)// token过期时间
                    .sign(algorithm); // 加密签名
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 校验token的有效性
     * @param token Token
     * @return 布尔值
     */
    public static boolean isValid(String token){
        if (token == null || token.isEmpty()){
            return false;
        }

        try {
            JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(JWT_SECRET)).build();
            DecodedJWT decodedJWT = jwtVerifier.verify(token);
            return new Date().before(decodedJWT.getExpiresAt());
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 校验当前用户token是否正确
     * @param token 密钥
     * @param username 用户名
     * @return 布尔值
     */
    public static boolean verify(String token, String username){
        try {
            Algorithm algorithm = Algorithm.HMAC256(JWT_SECRET);
            JWTVerifier verifier= JWT.require(algorithm)
                    .withClaim("username",username)
                    .build();
            DecodedJWT verified = verifier.verify(token);
            return true;
        } catch (Exception e) {
            return false;
        }
    }

    /**
     * 获取当前token中的用户名，无需secret解密也能获得
     * @param token String
     * @return token中包含的用户名信息
     */
    public static String getUsername(String token){
        try{
            DecodedJWT decodedJWT = JWT.decode(token);
            return decodedJWT.getClaim("username").asString();
        } catch (Exception e){
            return null;
        }
    }

    /**
     * 获取当前token中的用户权限，无需secret解密也能获得
     * @param token String
     * @return token中包含的用户名信息
     */
    public static List<String> getRoles(String token){
        List<String> roles = new ArrayList<>();

        try {
            DecodedJWT jwt = JWT.decode(token);

            String s = jwt.getClaim("roles").asString();

            String[] arr = s.split(",");

            for (String str :arr) {
                if (str == null || str.isEmpty())continue;
                roles.add(str);
            }
        } catch (JWTDecodeException e) {

        }
        return roles;
    }



}
